package com.dayaokeji.rhythmschoolstudent.client.common.seat.student_seat;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseEvent;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.CourseApi;
import com.dayaokeji.server_api.domain.Member;
import com.dayaokeji.server_api.domain.UpdateSeat;
import com.dayaokeji.server_api.domain.UserInfo;
import com.qfdqc.views.seattable.SeatTable;

import org.greenrobot.eventbus.EventBus;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 学生选座
 */
public class StudentSeatActivity extends BaseActivity {


    /**
     * 课程ID
     */
    public static final String EXTRA_COURSE_DETAIL_ID = "course_detail_id";
    public static final String EXTRA_COURSE_ID = "course_id";
    public static final String EXTRA_ROOM_ID = "room_id";
    public static final String EXTRA_MEMBER = "member";


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.seatView)
    SeatTable seatView;
    @BindView(R.id.tv_user_seat)
    TextView tvUserSeat;

    private Integer courseDetailId;

    private static final CourseApi courseApi = ApiUtils.getApi(CourseApi.class);
    private Call<ServerResponse<String>> getRoomSeatCall;

    private int mSeatRowNum;
    private int mSeatColumnNum;
    /**
     * 用户座位座次 ， [0] = row [1] = column
     */
    private int[] userSeatArray = new int[2];

    private UserInfo userInfo;
    private Call<ServerResponse<Void>> updateSeatCall;
    private int courseId;
    private int roomId;

    private Member member;
    private int[] userSeat;
    private int realUserColumn;
    private char[][] splitSeat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_seat);
        setSupportActionBar(toolbar);

        courseDetailId = getIntent().getIntExtra(EXTRA_COURSE_DETAIL_ID,-1);
        courseId = getIntent().getIntExtra(EXTRA_COURSE_ID, -1);
        roomId = getIntent().getIntExtra(EXTRA_ROOM_ID, -1);
        member = (Member) getIntent().getSerializableExtra(EXTRA_MEMBER);

        if (courseDetailId == -1 || courseId == -1 || roomId == -1 || member == null) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }

        init();
    }

    private void init() {
        setSeatView();
        userInfo = UserUtils.getUserInfo();
        if (userInfo == null) {
            ToastUtils.warning("当前账户异常");
            ActivityStackManager.finish();
            return;
        }
        getData();
        setupViewData();
    }

    @SuppressLint("SetTextI18n")
    private void setupViewData() {
        if (!TextUtils.isEmpty(member.getSeat())) {
            tvUserSeat.setText("座次："+member.getSeat());
        }else{
            tvUserSeat.setText("当前未选座");
        }
    }

    private void setSeatView() {
        userSeat = getUserSeat(member.getSeat());
        if (userSeat.length > 0) {
            seatView.setUserSeat(userSeat[0],userSeat[1]);
        }
        seatView.setMaxSelected(1);
//        seatView.setShowHeader(true);
    }

    @OnClick({R.id.btn_save_seat})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_save_seat:
                save();
                break;
        }
    }

    private void getData() {
        getRoomSeatCall = courseApi.getRoomSeat(courseDetailId);
        getRoomSeatCall.enqueue(new ServerCallback<String>(this,"加载中...") {

            @Override
            public void onResponse(boolean success, ServerResponse<String> response) {
                if (success) {
                    String seat = response.getBody();
                    if (!TextUtils.isEmpty(seat)) {
                        splitSeat = splitSeat(seat);
                        if (splitSeat != null) {
                            realUserColumn = getUserColumn(splitSeat);
                            if (seatView != null && realUserColumn != -1) {
                                seatView.setUserRealSeat((userSeat[0]-1),realUserColumn);
                            }
                            setSeatTableView(splitSeat);
                        }
                    }
                }
            }
        });
    }



    /**
     * 将座位排布字符串拆装成二维字符数组
     *
     * @param seat
     * @return
     */
    private char[][] splitSeat(String seat) {
        if (TextUtils.isEmpty(seat)) {
            return null;
        }
        String[] seatRows = seat.split("\r\n");
        mSeatRowNum = seatRows.length;
        mSeatColumnNum = seatRows[0].length();
        if (mSeatRowNum > 0 && mSeatColumnNum > 0) {
            char[][] seatArray = new char[mSeatRowNum][mSeatColumnNum];
            try{
                for (int i = 0; i < seatRows.length; i++) {
                    String seatRow = seatRows[i];
                    char[] chars = seatRow.toCharArray();
                    for (int j = 0; j < chars.length; j++) {
                        seatArray[i][j] = chars[j];
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            return seatArray;
        }
        return null;
    }

    /**
     * 设置排座View
     * @param seatArray
     */
    private void setSeatTableView(final char[][] seatArray) {
        seatView.setData(mSeatRowNum, mSeatColumnNum);
        seatView.setSeatChecker(new SeatTable.SeatChecker() {
            @Override
            public boolean isValidSeat(int row, int column) {

                if (seatArray != null) {
                    char c = seatArray[row][column];
                    if (c == '+') {
                        return false;
                    } else if (c == '@' || c == '-') {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public boolean isSold(int row, int column) {
                if (seatArray != null) {
                    char c = seatArray[row][column];
                    if (c == '-') {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public void checked(int row, int column) {
                userSeatArray[0] = row+1;
                userSeatArray[1] = ((column-getPlusColum(row,column))+1);
            }

            @Override
            public void unCheck(int row, int column) {

            }

            @Override
            public String[] checkedSeatTxt(int row, int column) {
//                return new String[]{(row+1)+"排"+((column-getPlusColum(row,column))+1)+"座"};
                return new String[]{};
            }
        });


    }

    /**
     * 验证是否选座了
     * @return
     */
    private boolean validate() {
        if (userSeatArray.length == 0) {
            ToastUtils.info("请先选座");
            return false;
        }else{
            return true;
        }
    }

    /**
     * 上传选座信息
     */
    private void save() {
        if (validate()) {
            if (userInfo != null) {
                final UpdateSeat updateSeat = new UpdateSeat();
                updateSeat.setCourseDetailId(courseDetailId);
                updateSeat.setRoomId(roomId);
                updateSeat.setStudentId(userInfo.getId());
                updateSeat.setSeat(userSeatArray[0]+"排"+userSeatArray[1]+"座");
                updateSeatCall = courseApi.updateSeat(updateSeat);
                updateSeatCall.enqueue(new ServerCallback<Void>() {
                    @Override
                    public void onResponse(boolean success, ServerResponse<Void> response) {
                        if (success) {
                            ToastUtils.success("选座成功");
                            UpdateCourseEvent updateCourseEvent = new UpdateCourseEvent();
                            updateCourseEvent.setUserSeat(updateSeat.getSeat());
                            EventBus.getDefault().post(updateCourseEvent);
                            ActivityStackManager.finish();
                        }
                    }
                });
            }else{
                ToastUtils.info("当前账户有误，请退出登录后重试");
            }
        }
    }


    /**
     * 正则解析用户座位座次
     *
     * @param userSeat
     * @return [0] = row  [1] = column
     */
    private int[] getUserSeat(String userSeat) {
        int[] userSeatArray = new int[2];
        String rgx = "(\\d+)([\\u4e00-\\u9fa5])(\\d+)([\\u4e00-\\u9fa5])";
        int row = 0;
        int column = 0;
        Pattern pattern = Pattern.compile(rgx);
        Matcher matcher = pattern.matcher(userSeat);
        if (matcher.find()) {
            row = Integer.valueOf(matcher.group(1));
            column = Integer.valueOf(matcher.group(3));
        }

        userSeatArray[0] = row;
        userSeatArray[1] = column;

        return userSeatArray;
    }

    /**
     * 得到用户实际的座位数
     * @param splitSeat
     * @return
     */
    private int getUserColumn(char[][] splitSeat) {
        int userRow = userSeat[0];
        int userColumn = userSeat[1];
        int index = 0 ;
        if (userSeat.length > 0 && userRow > 0 && userColumn > 0) {
            char[] chars = splitSeat[userRow-1];
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] == '@' || chars[i] == '-') {
                    index++;
                }
                if (index == userColumn){
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 得到不是座位的数目
     * @param row
     * @return
     */
    private int getPlusColum(int row,int colum) {
        int index = 0 ;
        if (splitSeat != null && splitSeat.length > 0) {
            char[] chars = splitSeat[row];
            for (int i = 0; i < colum; i++) {
                if (chars[i] == '+') {
                    index++;
                }
            }
        }
        return index;
    }


    @Override
    protected void onDestroy() {
        if (getRoomSeatCall != null) {
            getRoomSeatCall.cancel();
        }
        if (updateSeatCall != null) {
            updateSeatCall.cancel();
        }

        super.onDestroy();

    }
}
